
/*
 * GET home page.
 */
var sendTools = require('./send');
var fs = require('fs');
var path = require('path');
var pool = require('./../sql/mysql');

exports.reg = function(req, res){
    res.render('reg', { title: '用户注册'});
};
exports.doReg = function(req, res){
    var insertSQL = 'insert into zs_user(username,password,joindate) values(?,?,?)';
    pool.getConnection(function (err, conn) {
        var param = req.body;
        if (err) console.log("POOL ==> " + err);
        conn.query(insertSQL,[param.username,param.password,new Date()],function(err,info){
            if (err) {
                res.render('reg',{title: '用户注册结果',message:'注册失败！'});
            }else{
                res.render('reg',{title: '用户注册结果',message:'注册成功！'});
            }
//            console.info(info);
            conn.release();
        });
    });
}

exports.index = function(req, res){
res.render('index', { title: 'Index' });
};
exports.login = function(req, res){
res.render('login', { title: '用户登陆'});
};
exports.doLogin = function(req, res){
    pool.getConnection(function(err,conn){
        var param = req.body;
        var selectSQL = 'select id from zs_user where username = ? and password = ?';
        if (err) console.log("POOL ==> " + err);
        conn.query(selectSQL,[param.username,param.password],function(err,info){
            if (err) {
                res.render('login',{title: '登录提示',message:'登录失败！'});
            }else {
                var id = info[0]?info[0].id:null;
                if(id){
                    var user = {id:id,username:param.username,password:param.password};
                    res.render('home',{title:'个人中心',user:user});
                    req.session.user = user;
                    req.session.save();
                }else{
                    res.render('login',{title: '登录提示',message:'用户名或密码不正确！'});
                }
            }
    //            console.info(info);
            conn.release();
        });
    });
};
exports.logout = function(req, res){
	req.session.user = null;
res.redirect('/');
};

exports.upload = function(req,res){
	//res.writeHeader(200,{'Content-Type':'text/plain;charset=utf-8'});
    var data = {result:'000',files:[]};
    var files = req.files._files[0];//多文件上传数组
    if(!(files instanceof Array)){//单文件多文件的不同处理
        var tmp = files;
        files = [tmp];
    }
    var len = files.length;
    //单次请求文件数不超过10
    if(len>10){
        data.result = '001';
        res.send(JSON.stringify(data));
    }else{
        var exts = /\.xlsx?$/i;
        var maxSize = 2*1024*1024;//单次上传总大小2M
        for(var i=0;i<len;i++){
            var file = files[i];
            if(!exts.test(file.name)){
                data.result = '002';
                res.send(JSON.stringify(data));//不支持的文件类型
                break;
            }else{
                maxsize = maxSize-file.size;
                if(maxsize <0){
                    data.result = '003';
                    res.send(JSON.stringify(data));//单次上传超出大小
                    break;
                }
            }
        }
    }
    if(data.result == '000') {//上传成功的处理
        var total = 0;//移动文件处理完成数
        //开始移动文件
        for (var i=0;i<len;i++) {
            var file = files[i];
            // 获得文件的临时路径
            var tmp_path = file.path;
            // 指定文件上传后的目录
            var target_path = './public/files/' + file.name;
            // 移动文件
            (function(tmp_path,target_path,file){
                fs.rename(tmp_path, target_path, function (err) {
                    if (err) throw err;
                    // 删除临时文件夹文件
                    fs.unlink(tmp_path, function () {
                        total++;
                        if (err) throw err;
                        var ext = file.name.substring(file.name.lastIndexOf('.'));
                        data.files.push({ext: ext, name: file.name, size: file.size});
                        if(total == len){//全部处理完成
                            res.send(JSON.stringify(data));//直接send对象IE下存在问题
                        }
                    });
                });
            })(tmp_path,target_path,file);

        }
    }else{//上传失败 删除临时文件
            for (var i=0;i<len;i++){
                var file = files[i];
                var tmp_path = file.path;
                fs.unlink(tmp_path);
            }
        }
}
exports.send = function(req, res){
  sendTools.send(req,res);
};
exports.remove = function(req, res){
    var filename = req.body.name;
    var msg = 'success';
    fs.unlink(path.join('./public/files/',filename),function(err){
        if(err){
            msg = 'fail';
        }
        res.send(msg);
    })
};

exports.cfginfo = function(req, res){
    var selectSQL = 'select * from zs_mail where user_id = ?';
    pool.getConnection(function (err, conn) {
        var param = req.body;
        if (err) console.log("POOL ==> " + err);
        conn.query(selectSQL,[param.id],function(err,info){
            if (err) {
                res.send('fail');
            }else{
                res.send(info);
            }
//            console.info(info);
            conn.release();
        });
    });
}

exports.cfg = function(req, res){
    pool.getConnection(function (err, conn) {
        var param = req.body;
        if (err) console.log("POOL ==> " + err);
        if(param.cfgid){
            var updateSQL = 'update zs_mail set host =?,secure = ?,port = ?,user = ?,pass = ?,user_id = ?,intervals = ? where mail_id = ?';
            conn.query(updateSQL,[param.smtp,param.ssl,param.port,param.account,param.pass,param.id,param.interval,param.cfgid],function(err,info){
                if (err) {
                    console.log(err);
                    res.send('fail');
                }else{
                    res.send(info);
                }
                conn.release();
            });
        }else{
            var insertSQL = 'insert into zs_mail(host,secure,port,user,pass,intervals,user_id) values(?,?,?,?,?,?,?)';
            conn.query(insertSQL,[param.smtp,param.ssl,param.port,param.account,param.pass,param.interval,param.id],function(err,info){
                if (err) {
                    res.send('fail');
                }else{
                    res.send(info);
                }
                conn.release();
            });
        }

    })
};

exports.kindeditor = function(req,res){
    var obj = {error:0,url:'http://localhost:3000/sda.jpg'};
    res.send(JSON.stringify(obj));
}